#include "StdAfx.h"
#include "ships.h"
#include "ship.h"

const qreal defaultSpeed = 0.3;

Ships::Ships(const GameScenePtr gameScene, const GroupID id, const PlanetPtr sourcePlanet, 
             const PlanetPtr destinationPlanet, const PlayerID playerID, 
             const unsigned int percentToSend, bool inPercent, bool notifyOnArrival, QObject *parent)
            : QSequentialAnimationGroup(parent)
            , m_gameScene(gameScene)
            , m_id(id)
            , m_sourcePlanet(sourcePlanet)
            , m_destinationPlanet(destinationPlanet)
            , m_playerID(playerID)
            , m_percentToSend(percentToSend)
{
   if (!m_gameScene || !sourcePlanet || !destinationPlanet)
   {
      throw std::exception("Ships: m_gameScene || sourcePlanet || destinationPlanet cannot be NULL.");
   }
   const QPointF startPoint = sourcePlanet->pos();
   const QPointF endPoint = destinationPlanet->pos();
   const PlanetID p1ID = sourcePlanet->GetPlanetID();
   const PlanetID p2ID = destinationPlanet->GetPlanetID();
   qreal countOfShipsToSend = m_sourcePlanet->CountOfShips();
   if (inPercent)
   {
      countOfShipsToSend *= m_percentToSend / 100.0;
      m_sourcePlanet->CountOfShips(m_sourcePlanet->CountOfShips() - countOfShipsToSend);
   }
   else
   {
      m_sourcePlanet->CountOfShips(m_sourcePlanet->CountOfShips() - m_percentToSend);
   }

   m_ship = boost::make_shared<Ship>(destinationPlanet, countOfShipsToSend, playerID, -m_gameScene->angle(p1ID,p2ID), notifyOnArrival);
   m_ship->setPos(sourcePlanet->pos());
   m_gameScene->addItem(m_ship.get());
   QEasingCurve curve(QEasingCurve::InOutSine);
   m_propertyAnimation = boost::make_shared<QPropertyAnimation>(m_ship.get(), "pos");
   m_propertyAnimation->setStartValue(sourcePlanet->pos());
   m_propertyAnimation->setEndValue(destinationPlanet->pos());
   m_propertyAnimation->setEasingCurve(curve);
   m_propertyAnimation->setDuration(m_gameScene->distance(p1ID, p2ID) / defaultSpeed);
   addAnimation(m_propertyAnimation.get());
   QObject::connect(m_ship.get(), SIGNAL(arrivedToPlanet(ShipPtr, const PlanetPtr, const unsigned int, const PlayerID)), m_gameScene.get(), SLOT(newShipsArrived(ShipPtr, const PlanetPtr, const unsigned int, const PlayerID)));
}

Ships::~Ships()
{
   disconnectSignals();
   m_ship.reset();
}

void Ships::disconnectSignals()
{
   disconnect();
   dumpObjectInfo();
}